package com.example.spring.transaction.service;

import com.example.spring.transaction.dal.IUserDao;
import com.example.spring.transaction.dal.User;
import jakarta.annotation.Resource;
import lombok.Setter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author lei yu
 * @since 2024/06/05
 */
@Service
@Setter
public class UserServiceImpl implements IUserService {

    @Resource
    private IUserDao userDao;

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public User getUser() {
        return userDao.getUser();
    }

    @Override
    @Transactional(timeout = 2, rollbackFor = Exception.class)
    public void sub() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("SMITH扣钱");
        userDao.sub();
    }

    @Transactional(rollbackFor = {RuntimeException.class})
    @Override
    public void tranException() throws RuntimeException {
        System.out.println("SMITH准备扣钱");
        userDao.sub();
        throw new RuntimeException("测试");
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void trans() {
        sub();
        save();
    }


    public void save() {
        System.out.println("ALLEN加钱");
        int i=1/0;
        userDao.save();
    }


}
